package com.xuecheng.order.mq;

import com.xuecheng.framework.domain.task.XcTask;
import com.xuecheng.order.config.RabbitMQConfig;
import com.xuecheng.order.service.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author Kidy
 * @date 2020/7/17 21:45
 */
@Component
public class ChooseCourseTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(ChooseCourseTask.class);

    @Autowired
    private TaskService taskService;

    @RabbitListener(queues = RabbitMQConfig.XC_LEARNING_FINISHADDCHOOSECOURSE)
    public void receiveFinishChooseCourseTask(XcTask xcTask) {
        if (null != xcTask && StringUtils.isNotBlank(xcTask.getId())) {
            taskService.finishTask(xcTask.getId());
        }
    }

    //    @Scheduled(cron = "0 0/1 * * * *")
    @Scheduled(fixedRate = 3000)
    public void sendChooseCourseTask() throws InterruptedException {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE, -1);
        Date time = calendar.getTime();
        List<XcTask> xcTaskList = taskService.findXcTaskList(time, 100);
        xcTaskList.forEach(xcTask -> {
            if (taskService.getTask(xcTask.getId(), xcTask.getVersion()) > 0) {
                taskService.publish(xcTask, xcTask.getMqExchange(), xcTask.getMqRoutingkey());
            }
        });
    }

    //    @Scheduled(cron = "0 0/1 * * * *")
    //    @Scheduled(fixedRate = 3000)
    public void task01() throws InterruptedException {
        LOGGER.info("============11111111开始============");
        Thread.sleep(5 * 1000);
        LOGGER.info("============11111111结束============");
    }

    //    @Scheduled(fixedRate = 3000,zone = "1")
    public void task02() throws InterruptedException {
        LOGGER.info("============22222222开始============");
        Thread.sleep(5 * 1000);
        LOGGER.info("============22222222结束============");
    }
}
